package com.mspbots.cw.amqp.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.cw.amqp.BaseReceiver;
import com.mspbots.cw.amqp.model.ExceptionLog;
import com.mspbots.cw.amqp.model.SheetsTime;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * com.mspbots.core.amqp.receivers.TSheetsTimeReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/30
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class SheetsTimeReceiver extends BaseReceiver {

    private final RabbitMessagingTemplate messagingTemplate;

    @RabbitListener(queues = "core.sheet.times")
    public void processMessage(SheetsTime content) {
        try{
            log.info("msp.attendance.sheet.times::  {}",content);

            this.databaseClient.execute("select id from tsheet_times " +
                    "where sheet_id=:sheetId and tenant_id =:tenantId")
                    .as(Long.class)
                    .bind("tenantId", content.getTenantId())
                    .bind("sheetId", content.getSheetId())
                    .fetch()
                    .one()
                    .filter(id -> id > 0)
                    .switchIfEmpty(
                            this.databaseClient.insert().into(SheetsTime.class).using(content)
                                    .fetch().rowsUpdated().map(Long::valueOf)
                                    .doOnNext(re -> {
                                        log.debug("Receiver sheets time entry install size  {}", re);
                                        content.setNotes("insert::"+content.getSheetId());
                                        messagingTemplate.convertAndSend("msp.attendance.sheet.times","",content);
                                        log.info("msp.attendance.sheet.times insert::");
                                    })
                    )
                    .doOnNext(id -> log.debug("Receiver sheets time entry id {}", id))
                    .flatMap(id -> {
                        log.info("msp.attendance.sheet.times update::");
                        content.setNotes("update::"+content.getSheetId());
                        //messagingTemplate.convertAndSend("msp.attendance.sheet.times","",content);
                        content.setId(id);
                        content.setSyncTime(LocalDateTime.now());
                        return this.databaseClient.update().table(SheetsTime.class)
                                .using(content).fetch().rowsUpdated();
                    }).block();
        }catch (Exception e){
            this.databaseClient.insert().into(ExceptionLog.class).using(
                    ExceptionLog.builder()
                            .tenantId(content.getTenantId().intValue())
                            .name("core.sheet.times")
                            .status(500)
                            .type("core.sheet.times")
                            .msg(e.getMessage()+","+objectMapper.convertValue(content, JsonNode.class).toString() )
                            .build()
            ).fetch().rowsUpdated().block(Duration.ofSeconds(10));
        }
    }
}
